<template>
  <CommonNav title="错题本">
    <template v-slot:search>
      <button class="btn btn-active btn-primary btn-sm" @click="questionsClick">
        错题练习
      </button>
      <label class="input input-sm">
        <svg class="h-[1.5em] opacity-50" viewBox="0 0 24 24">
          <g
            stroke-linejoin="round"
            stroke-linecap="round"
            stroke-width="2.5"
            fill="none"
            stroke="currentColor"
          >
            <circle cx="11" cy="11" r="8"></circle>
            <path d="m21 21-4.3-4.3"></path>
          </g>
        </svg>
        <input
          type="search"
          class="grow text-sm"
          placeholder="搜索错题，输入关键字"
          v-model="searchKeyword"
          @input="debouncedSearch"
          ref="searchInput"
        />
        <kbd class="kbd kbd-sm">⌘</kbd>
        <kbd class="kbd kbd-sm">K</kbd>
      </label>
    </template>
  </CommonNav>
  <CommonMain>
    <CommonLack v-if="!data.length" content="暂无错题！" />
    <div
      v-for="(item, index) in data"
      :key="index"
      class="card bg-base-100 shadow-lg hover:shadow-md transition-shadow duration-200 w-full my-4 cursor-pointer"
    >
      <div class="card-body p-4 flex flex-col sm:flex-row items-center gap-4">
        <div class="badge badge-primary badge-lg">{{ index + 1 }}</div>
        <div class="flex-grow">
          <h2 class="card-title text-primary mb-1">
            {{ item.content?.english }}
          </h2>
          <p class="text-base-content/70">{{ item.content?.chinese }}</p>
          <div
            class="md:flex md:flex-row items-center gap-3 text-base-content/60 text-sm text-gray-500"
          >
            <BookOpenIcon class="w-4 h-4" />
            <span
              >{{ item.chapter?.course?.title }} /
              {{ item.chapter?.title }}</span
            >
            <ClockIcon class="w-4 h-4" />
            <span>{{ getDateTime(item.createdAt) }}</span>
            <div role="alert" class="alert alert-warning alert-dash py-1 px-2">
              <ExclamationCircleIcon class="w-4 h-4" />
              <span>错误次数 {{ item.errNumber }}</span>
            </div>
          </div>
        </div>
        <button
          class="btn btn-circle btn-ghost btn-sm"
          @click="playAudio(item.content?.english)"
        >
          <SpeakerWaveIcon class="w-5 h-5" />
        </button>
      </div>
    </div>
    <div
      ref="loadingTrigger"
      class="h-10 flex items-center justify-center"
    ></div>
  </CommonMain>

  <Modal
    title="错题练习"
    :isOpen="questionsStatus"
    @close="questionsStatus = false"
  >
    <div class="w-[30rem] space-y-5">
      <div class="text-base font-medium">练习模式</div>
      <div class="flex gap-4">
        <button class="btn btn-soft btn-primary flex-1"
        :class="[{
          'btn-active':modeIndex===index,
        }]"
        @click="modeIndex=index"
        v-for="item,index in modes">{{ item.tilte }}</button>
      </div>
      <div class="text-base font-medium">练习类型</div>
      <div class="flex gap-4">
        <button class="btn btn-soft btn-primary flex-1"
        :class="[{
          'btn-active':typeIndex===index,
        }]"
        @click="typeIndex=index"
        v-for="item,index in types">{{ item.tilte }}</button>
      </div>
      <button class="btn btn-soft  btn-primary btn-active  w-full" @click="startQuestions">开始练习</button>
    </div>
  </Modal>
</template>
<script setup>
import {
  SpeakerWaveIcon,
  ClockIcon,
  BookOpenIcon,
  ExclamationCircleIcon,
} from "@heroicons/vue/24/solid";
import { timeSet } from "~/composables/common/time";
import { useDebounceFn } from "@vueuse/core";
import {
  registerShortcut,
  cancelShortcut,
} from "~/composables/user/globalShortcut";
import { getErrbookList } from "~/composables/user/errbook";
import { usePlayAudio } from "~/composables/common/playAudio";
import { useIntersectionObserver } from "@vueuse/core";

const { getDateTime } = timeSet();
const { playAudio } = usePlayAudio();
const data = ref([]);
const searchKeyword = ref("");
const searchInput = ref(null);
const page = ref(0);
const size = ref(10);
const loadMore = async () => {
  try {
    const newData = await getErrbookList(
      searchKeyword.value,
      page.value + 1,
      size.value
    );
    if (newData && newData.length > 0) {
      data.value = [...data.value, ...newData];
      page.value++;
    }
  } catch (error) {
    console.error("加载更多错题失败:", error);
  }
};
const debouncedSearch = useDebounceFn(async () => {
  page.value = 1;
  data.value = await getErrbookList(
    searchKeyword.value,
    page.value,
    size.value
  );
}, 300);

const registeredShortcuts = [];
onMounted(async () => {
  registeredShortcuts.push(
    registerShortcut(
      "ctrl+k",
      (e) => {
        e.preventDefault();
        searchInput.value?.focus();
      },
      { priority: "high" }
    )
  );
});
onUnmounted(() => {
  registeredShortcuts.forEach((shortcut) => {
    cancelShortcut(shortcut);
  });
});

const loadingTrigger = ref(null);
useIntersectionObserver(
  loadingTrigger,
  ([{ isIntersecting }]) => {
    if (isIntersecting) {
      loadMore();
    }
  },
  { rootMargin: "100px" }
);
const questionsStatus = ref(true);
const questionsClick = () => {
  questionsStatus.value = true;
};
const modeIndex = ref(0);
const typeIndex = ref(0);
const modes=[
  {
    tilte: "汉译英模式",
    type: "chinese_to_english",
  },
  {
    tilte: "听写模式",
    type: "listen_to_write",
  },
  // {
  //   tilte: "答题模式",
  //   type: "listen_to_write",
  // },
];
const types=[
  {
    tilte: "最近错题",
    type: "createdAt", 
  },
  {
    tilte: "高频错题",
    type: "errNumber",
  },
]

const startQuestions = () => {
  navigateTo({
    path: '/study/err/input',
    query: {
      type: modes[modeIndex.value].type,
      sort: types[typeIndex.value].type,
    }
  });
  questionsStatus.value = false;
};
</script>
